/* 
 * Document   : foam-script
 * Created on : 15 mai 2013, 09:23:43
 * Author     : Mamy RAKOTONIRINA
 * Description: JS for FOAM
 */


$(document).ready(function() {
    var navIdx = 100;
    var uri = document.location.pathname; 
    var icons = {
        header: "ui-icon-carat-1-e",
        activeHeader: "ui-icon-carat-1-s"
    };
    
    if(uri.match(/produit/) || uri.match(/carte/)){
        navIdx = 1;
    } else if(uri.match(/tableaudebord/) || uri.match(/synthese/)) {
        navIdx = 2;
    } else {
        navIdx = 0;
    }
    
    $( "#nav-cube" ).accordion({
        icons: icons,
        active: navIdx,
        heightStyle: "content"
    });
    
    $(".datepicker").datepicker({
        maxDate: '+0D', 
        dateFormat: "yy-mm-dd",
        dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'], 
        dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'], 
        monthNamesShort: ['Jan','Fev','Mar','Avr','Mai','Jun','Jul','Août','Sep','Oct','Nov','Déc'], 
        monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'], 
        prevText: 'Précédent', 
        nextText: 'Suivant'	
    });
    
    $("#startDate").datepicker({
        maxDate: '+0D',
        dateFormat: 'dd/mm/yy', 
        altFormat: "yy-mm-dd",
        altField: '#altStartDate',
        dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'], 
        dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'], 
        monthNamesShort: ['Jan','Fev','Mar','Avr','Mai','Jun','Jul','Août','Sep','Oct','Nov','Déc'], 
        monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'], 
        prevText: 'Précédent', 
        nextText: 'Suivant'
    });
    
    $("#endDate").datepicker({
        maxDate: '+0D',
        dateFormat: 'dd/mm/yy', 
        altFormat: "yy-mm-dd",
        altField: '#altEndDate',
        dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'], 
        dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'], 
        monthNamesShort: ['Jan','Fev','Mar','Avr','Mai','Jun','Jul','Août','Sep','Oct','Nov','Déc'], 
        monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'], 
        prevText: 'Précédent', 
        nextText: 'Suivant'
    });
    
    var checkboxHeight = "16";
    var radioHeight = "16";
    var Custom = {
	init: function() {
            var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
            for(var a = 0; a < inputs.length; a++) {
                if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
                    span[a] = document.createElement("span");
                    span[a].className = inputs[a].type;

                    if(inputs[a].checked == true) {
                        if(inputs[a].type == "checkbox") {
                            var position = "0 -" + (checkboxHeight) + "px";
                            span[a].style.backgroundPosition = position;
                        } else {
                            var position = "0 -" + (radioHeight) + "px";
                            span[a].style.backgroundPosition = position;
                        }
                    }
                    inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                    inputs[a].onchange = Custom.clear;
                    if(!inputs[a].getAttribute("disabled")) {
                        span[a].onmousedown = Custom.pushed;
                        span[a].onmouseup = Custom.check;
                    } else {
                        span[a].className = span[a].className += " disabled";
                    }
                }
            }
            inputs = document.getElementsByTagName("select");
            for(var a = 0; a < inputs.length; a++) {
                if(inputs[a].className == "styled") {
                    option = inputs[a].getElementsByTagName("option");
                    active = option[0].childNodes[0].nodeValue;
                    textnode = document.createTextNode(active);
                    for(var b = 0; b < option.length; b++) {
                        if(option[b].selected == true) {
                            textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
                        }
                    }
                    span[a] = document.createElement("span");
                    span[a].className = "select";
                    span[a].id = "select" + inputs[a].name;
                    span[a].appendChild(textnode);
                    inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                    if(!inputs[a].getAttribute("disabled")) {
                        inputs[a].onchange = Custom.choose;
                    } else {
                        inputs[a].previousSibling.className = inputs[a].previousSibling.className += " disabled";
                    }
                }
            }
            document.onmouseup = Custom.clear;
	},
	pushed: function() {
            var element = this.nextSibling;
            if(element.checked == true && element.type == "checkbox") {
                this.style.backgroundPosition = "0 0";
            } else if(element.checked == true && element.type == "radio") {
                this.style.backgroundPosition = "0 0";
            } else if(element.checked != true && element.type == "checkbox") {
                this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
            } else {
                this.style.backgroundPosition = "0 -" + radioHeight + "px";
            }
	},
	check: function() {
            var element = this.nextSibling;
            if(element.checked == true && element.type == "checkbox") {
                this.style.backgroundPosition = "0 0";
                //element.checked = false;
                //$(element).checked(false);
                element.prop('checked', false);
            } else {
                if(element.type == "checkbox") {
                    this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
                } else {
                    this.style.backgroundPosition = "0 -" + radioHeight + "px";
                    var group = this.nextSibling.name;
                    var inputs = document.getElementsByTagName("input");
                    for(var a = 0; a < inputs.length; a++) {
                        if(inputs[a].name == group && inputs[a] != this.nextSibling) {
                            inputs[a].previousSibling.style.backgroundPosition = "0 0";
                        }
                    }
                }
                //element.checked = true;
                //$(element).checked(true);
                element.prop('checked', true);
            }
	},
	clear: function() {
            var inputs = document.getElementsByTagName("input");
            for(var b = 0; b < inputs.length; b++) {
                if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight + "px";
                } else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 0";
                } else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight + "px";
                } else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 0";
                }
            }
	},
	choose: function() {
            var option = this.getElementsByTagName("option");
            for(var d = 0; d < option.length; d++) {
                if(option[d].selected == true) {
                    document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
                }
            }
	}
    };
    window.onload = Custom.init;
});

$.event.special.hoverintent = {
    setup: function() {
        $( this ).bind( "mouseover", jQuery.event.special.hoverintent.handler );
    },
    teardown: function() {
        $( this ).unbind( "mouseover", jQuery.event.special.hoverintent.handler );
    },
    handler: function( event ) {
        var currentX, currentY, timeout,
            args = arguments,
            target = $( event.target ),
            previousX = event.pageX,
            previousY = event.pageY;
    
        function track( event ) {
            currentX = event.pageX;
            currentY = event.pageY;
        };
        
        function clear() {
            target
                .unbind( "mousemove", track )
                .unbind( "mouseout", clear );
            clearTimeout( timeout );
        }
        function handler() {
            var prop,
                orig = event;
        
            if ( ( Math.abs( previousX - currentX ) +
            Math.abs( previousY - currentY ) ) < 7 ) {
                clear();
                event = $.Event( "hoverintent" );
                for ( prop in orig ) {
                    if ( !( prop in event ) ) {
                        event[ prop ] = orig[ prop ];
                    }
                }
                delete event.originalEvent;
                target.trigger( event );
            } else {
                previousX = currentX;
                previousY = currentY;
                timeout = setTimeout( handler, 100 );
            }
        }
        timeout = setTimeout( handler, 100 );
        target.bind({
        mousemove: track,
        mouseout: clear
        });
    }
};

function listbox_selectall(listID, isSelect) {
    var listbox = document.getElementById(listID);
    for(var count=0; count < listbox.options.length; count++) {
        listbox.options[count].selected = isSelect;
    }
}

function listbox_moveacross(sourceID, destID) {
    var src = document.getElementById(sourceID);
    var dest = document.getElementById(destID);
    
    for(var count=0; count < src.options.length; count++) {
        if(src.options[count].selected == true) {
            var option = src.options[count];
            var newOption = document.createElement("option");
            newOption.value = option.value;
            newOption.text = option.text;
            newOption.selected = true;
            try {
                dest.add( newOption, null); //Standard
                src.remove(count, null);
            }catch(error) {
                dest.add( newOption); //Standard
                //dest.add(newOption); // IE only
                src.remove(count);
            }
            count--;
        }
    }
}

function sortlist(mylist) {
    var lb = document.getElementById(mylist);
    var arrTexts = new Array();
    
    for(i=0; i<lb.length; i++)  {
        arrTexts[i].text = lb.options[i].text;
        arrTexts[i].value = lb.options[i].value;
    }
    
    arrTexts.sort();
    
    for(i=0; i<lb.length; i++)  {
        lb.options[i].text = arrTexts[i].text;
        lb.options[i].value = arrTexts[i].value;
    }
}

function dateToYMD(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

function dateToDMY(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return '' + (d <= 9 ? '0' + d : d) + '/' + (m<=9 ? '0' + m : m) + '/' + y;
}


function cDelete(id){
    // Manage Uri
    var uri = document.location.pathname;
    
    if(confirm('Voulez vous vraiment supprimé?')){
        window.location.href = uri+'/delete/'+id;
    }
}

function attribProduit(id){
    // Manage Uri
    var uri = document.location.pathname;
    
    window.location.href = uri+'/attribproduit/'+id;
}

function otherCancel(controller){
    // Get foamUri
    var uri = document.location.pathname;
    var foamPos = uri.lastIndexOf("foam");
    var resteUri = uri.substring(foamPos,100);
    var foamUri = uri.replace(resteUri, "foam");
    
    window.location.href = foamUri+'/'+controller; 
}

function multiSelectAll(choice) {
    $('.selectable').multiSelect(choice);
    return false;
}

function checkMe(el, action){   
    var uri = document.location.pathname;
    var foamPos = uri.lastIndexOf("foam");
    var resteUri = uri.substring(foamPos,100);
    var baseUri = uri.replace(resteUri, "");
    
    var allCb = $(".content-body-top").find(':checkbox'); 
    var chk = $(el).children('input');
    var loading = '<td class="loading" style="text-align:center;padding:20px"><img src="'+baseUri+'/img/foam/loader.gif" alt="loading" /></td>'; 
    var loading2 = '<p class="loading" style="text-align:center;padding:20px"><img src="'+baseUri+'/img/foam/loader.gif" alt="loading" /></p>';
    
    if(chk.is(':checked')){
        // Disabled other checkbox
        allCb.prop('checked', false);
        
        // Enabled this checkbox
        chk.prop('checked', true);
        
        if(action == 'synthese') {
            $('.content-body-top').css('padding', '10px 0 10px 60px');
            $(".content-body-bottom").html(loading);
            showMe(action, '');            
        } else if(action == 'detail') { 
            $("#a-month-detail").editable('option', 'disabled', false);
            $("#a-month-detail").editable('option', 'validate', function(v) { 
                $("#a-month-detail").css('color', '#6299DF');
                $('.content-body-top').css('padding', '10px 0');
                $(".content-body-bottom").html(loading);
                showMe(action, v.format("YYYY-MM-DD"));                
            });
        } else if(action == 'retro') {
            $('.content-body-top').css('padding', '10px 0 10px 60px');
            $(".content-body-bottom").html(loading);
            showMe('synthese', '');
            
            $("#a-month1-retro").editable('option', 'disabled', false);
            $("#a-month2-retro").editable('option', 'disabled', false);
            
            $("#a-month1-retro").editable('option', 'validate', function(v) {
                $("#a-month1-retro").css('color', '#6299DF');
                $(".content-body-right-moisa").html(loading2);
                $(".month-header.moisa p").text(v.format("MMMM YYYY"));
                showRetro1(v.format("YYYY-MM-DD"));                
            });
            
            $("#a-month2-retro").editable('option', 'validate', function(v) {
                $("#a-month2-retro").css('color', '#6299DF');
                $(".content-body-right-moisb").html(loading2);
                $(".month-header.moisb p").text(v.format("MMMM YYYY"));
                showRetro2(v.format("YYYY-MM-DD"));                
            });
        }
    } else { 
        // Disabled all checkbox
        allCb.prop('checked', false);
        $("#a-month-detail").editable('option','disabled',true);
        $("#a-month1-retro").editable('option', 'disabled', true);
        $("#a-month2-retro").editable('option', 'disabled', true);
        
        $("#a-month-detail").css('color', '#FFFFFF');
        $("#a-month1-retro").css('color', '#FFFFFF');
        $("#a-month2-retro").css('color', '#FFFFFF');
        
        $(".month-header.moisa p").text('mois a');
        $(".month-header.moisb p").text('mois b');
    }
}   
    
    
function showMe(action, month) {
    var uri = document.location.pathname;
    var foamPos = uri.lastIndexOf("foam");
    var resteUri = uri.substring(foamPos,100);
    var foamUri = uri.replace(resteUri, "foam");
    
    $.ajax({
        type: 'POST',
        url: foamUri+'/tableaudebord/'+action,
        dataType: "html",
        cache: false,
        data: { month: month },
        success: function(contenu){  
            $(".content-body-bottom").css('display','none');
            $(".content-body-bottom").html(contenu);
            $(".content-body-bottom").fadeIn('slow');
            
            var rotate_container = $(".section-famille").find('.rotate-container');
            
            rotate_container.each(function(){
                var hisRotate = $(this).find('.rotate');
                var hisRotateWidth = hisRotate.width();
                
                $(this).height(hisRotateWidth);
                hisRotate.width(20);
            });
        }
    }); 
}

function showRetro1(month) {
    var uri = document.location.pathname;
    var foamPos = uri.lastIndexOf("foam");
    var resteUri = uri.substring(foamPos,100);
    var foamUri = uri.replace(resteUri, "foam");
    
    $.ajax({
        type: 'POST',
        url: foamUri+'/tableaudebord/retro',
        dataType: "html",
        cache: false,
        data: { month: month },
        success: function(contenu){  
            $(".content-body-right-moisa").css('display','none');
            $(".content-body-right-moisa").html(contenu);
            $(".content-body-right-moisa").fadeIn('slow');
        }
    }); 
}

function showRetro2(month) {
    var uri = document.location.pathname;
    var foamPos = uri.lastIndexOf("foam");
    var resteUri = uri.substring(foamPos,100);
    var foamUri = uri.replace(resteUri, "foam");
    
    $.ajax({
        type: 'POST',
        url: foamUri+'/tableaudebord/retro',
        dataType: "html",
        cache: false,
        data: { month: month },
        success: function(contenu){  
            $(".content-body-right-moisb").css('display','none');
            $(".content-body-right-moisb").html(contenu);
            $(".content-body-right-moisb").fadeIn('slow');
        }
    }); 
}